#include <WinSock2.h>
#include <iostream>

//#define TG_TRANSSERVER_PORT 5021

// for debug by dzlua
#define TG_TRANSSERVER_PORT 25092

bool ConnectTransServer(char* ipstr);
SOCKET g_socket;

int main(int argc, char* argv[])
{
	WSADATA wsaData;
	int err;
	err = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (ConnectTransServer("127.0.0.1")) {
		char* buf = "hello server!1"
					"hello server!2"
					"hello server!3";
		char recvbuf[1024] = { 0 };
		while(true) {
			unsigned short len = strlen(buf)+1;
			//len = htons(len);
			send(g_socket, (char*)&len, sizeof(unsigned short), 0);
			send(g_socket, buf, len, 0);
			recv(g_socket, recvbuf, 1024, 0);
			printf("%s\r\n",recvbuf+sizeof(unsigned short));
			Sleep(1000);
		}
	}
	WSACleanup();
	return 0;
}

bool ConnectTransServer(char* ipstr) {
	bool ret = false;
	g_socket = socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in remoteaddr;
	remoteaddr.sin_family = AF_INET;
	remoteaddr.sin_port = htons(TG_TRANSSERVER_PORT);
	remoteaddr.sin_addr.S_un.S_addr = inet_addr(ipstr);
	if (connect(g_socket, (sockaddr*)&remoteaddr, sizeof(sockaddr_in)) < 0) {
		printf("error %d\r\n", GetLastError());
	}
	ret = true;
	return ret;
}
